import { Request, Response, NextFunction } from 'express';
import { AuthUser } from '../types/auth';
import Question from '../models/question';
import { Errors } from '../types/errors';

interface RequestWithUser extends Request {
  user?: AuthUser;
}

export class QuestionController {
  static async create(req: RequestWithUser, res: Response, next: NextFunction) {
    try {
      const { title, content, type, difficulty, tags } = req.body;
      const user = req.user;

      if (!title || !content || !type || !difficulty) {
        throw Errors.badRequest('Missing required fields');
      }

      const question = await Question.create({
        title,
        content,
        type,
        difficulty,
        tags: tags || [],
        createdBy: user!._id,
        status: 'active'
      });

      res.status(201).json({
        message: 'Question created successfully',
        data: question
      });
    } catch (error) {
      next(error);
    }
  }

  static async list(req: RequestWithUser, res: Response, next: NextFunction) {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const skip = (page - 1) * limit;

      const query: any = { status: 'active' };
      if (req.query.type) {
        query.type = req.query.type;
      }

      const [questions, total] = await Promise.all([
        Question.find(query)
          .skip(skip)
          .limit(limit)
          .sort({ createdAt: -1 })
          .populate('createdBy', 'name'),
        Question.countDocuments(query)
      ]);

      res.json({
        data: questions,
        pagination: {
          page,
          limit,
          total
        }
      });
    } catch (error) {
      next(error);
    }
  }

  static async update(req: RequestWithUser, res: Response, next: NextFunction) {
    try {
      const { id } = req.params;
      const updates = req.body;
      const user = req.user;

      const question = await Question.findOneAndUpdate(
        { _id: id, status: 'active' },
        { 
          ...updates,
          updatedBy: user!._id
        },
        { new: true }
      );

      if (!question) {
        throw Errors.notFound('Question not found');
      }

      res.json({
        message: 'Question updated successfully',
        data: question
      });
    } catch (error) {
      next(error);
    }
  }

  static async delete(req: RequestWithUser, res: Response, next: NextFunction) {
    try {
      const { id } = req.params;
      const user = req.user;

      const question = await Question.findOneAndUpdate(
        { _id: id, status: 'active' },
        { 
          status: 'deleted',
          updatedBy: user!._id
        },
        { new: true }
      );

      if (!question) {
        throw Errors.notFound('Question not found');
      }

      res.json({
        message: 'Question deleted successfully',
        data: question
      });
    } catch (error) {
      next(error);
    }
  }

  static async batchDelete(req: RequestWithUser, res: Response, next: NextFunction) {
    try {
      const { ids } = req.body;
      const user = req.user;

      if (!Array.isArray(ids)) {
        throw Errors.badRequest('Invalid request body');
      }

      const result = await Question.updateMany(
        { 
          _id: { $in: ids },
          status: 'active'
        },
        { 
          status: 'deleted',
          updatedBy: user!._id
        }
      );

      res.json({
        message: 'Questions deleted successfully',
        data: {
          modifiedCount: result.modifiedCount
        }
      });
    } catch (error) {
      next(error);
    }
  }
}
